package com.mujin.keji.collectionsystem.module.login.repository;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.base.BaseDto;
import com.mujin.keji.collectionsystem.base.CommonRepository;
import com.mujin.keji.collectionsystem.common.ErrorEnum;
import com.mujin.keji.collectionsystem.db.dao.UserDao;
import com.mujin.keji.collectionsystem.db.database.AppDataBase;
import com.mujin.keji.collectionsystem.exception.ServerException;
import com.mujin.keji.collectionsystem.http.HttpUtils;
import com.mujin.keji.collectionsystem.module.login.dto.LoginDto;
import com.mujin.keji.collectionsystem.module.login.dto.UserDto;
import com.mujin.keji.collectionsystem.module.login.syncData.SyncDataThread;
import com.mujin.keji.collectionsystem.module.login.views.LoginActivity;
import com.mujin.keji.collectionsystem.module.login.vo.LoginCollectionVo;
import com.mujin.keji.collectionsystem.module.login.vo.LoginVo;
import com.mujin.keji.collectionsystem.net.NetworkUtil;
import com.mujin.keji.collectionsystem.utils.Dom4jUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.SPUtil;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

import okhttp3.Response;

import static com.mujin.keji.collectionsystem.utils.IpUtils.getIPAddress;
import static com.mujin.keji.collectionsystem.utils.IpUtils.internalIp;

/**
 * 登陆Repository
 *
 * @author weishixiong
 * @Time 2018-03-30
 */
public class LoginRepository extends CommonRepository<LoginDto> implements ILoginRepository {

    private static final String TAG = "login";

    private ConnectivityManager manager;
    /**
     * 登录接口
     * 判断是内网还是外网
     * 1、内网  调用登陆的接口，获取session，同步数据（保存或更新本地库用户信息）
     * 2、外网  查询本地库是否有记录，有--->登陆成功；无---->登陆失败
     *
     * @param vo
     * @return
     */
    private LoginActivity activity;

    public BaseDto<LoginDto> login(LoginVo vo, Context context, LoginActivity activity) {
        this.activity = activity;
        manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        UserDao userDao = AppDataBase.getInstance(context).getUserDao();
        String session = "";
        String ip = getIPAddress(context);
        if (StringUtils.isBlank(ip)) {
            Message msg = Message.obtain();
            msg.obj = ErrorEnum.ERROR_10003.getMessage();
            activity.getHandler().sendMessage(msg);
            return new BaseDto<>(300, "");
        }

        NetworkInfo.State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        UserDto userDto = userDao.findUserByUserName(vo.getUsername());

        //判断有没有网，有网 走网络，没网走本地
        if (NetworkUtil.isNetworkConnected(context)) {

            Log.i(TAG, "当前为内网状态，获取session");
            session = getLoginSession(vo);
            SPUtil.putData(Constant.SP.SP,"session",session);
            Log.i(TAG, "获取的登陆session:" + session);
            if (StringUtils.isNotBlank(session))
            {
                if (userDto == null) {//用户不存在添加用户
                    userDto = new UserDto();
                    userDto.setUsername(vo.getUsername());
                    userDto.setPassword(vo.getPassword());
                    Log.i(TAG, "本地库不存在该用户，新增:" + JSONObject.toJSONString(userDto));

                    userDao.addUser(userDto);
                    SPUtil.putData(Constant.SP.SP, Constant.SP.USER, userDto.getUsername());
                } else if (!userDto.getPassword().equals(vo.getPassword())) {
                    //密码和本地库不一致，更新本地库密码
                    userDto.setPassword(vo.getPassword());
                    Log.i(TAG, "密码和本地库不一致，更新本地库密码:" + JSONObject.toJSONString(userDto));
                    userDao.updateUser(userDto);
                    SPUtil.putData(Constant.SP.SP, Constant.SP.USER, userDto.getUsername());
                } else {
                    //设置sp值
                    SPUtil.putData(Constant.SP.SP, Constant.SP.USER, userDto.getUsername());
                }
                //同步数据线程
//                SyncDataThread syncDataThread = new SyncDataThread(context, session, userDto.getUsername(), activity);
//                syncDataThread.start();
                LoginDto loginDto = new LoginDto();
                if (userDto != null) {
                    loginDto.setUserAccount(userDto.getUsername());
                    loginDto.setUserName(userDto.getUsername());

                }
                loginDto.setNeedSysData("1");
                return new BaseDto(loginDto);

            }
            //服务器登录失败
            else {
                return new BaseDto<>(300, "");

            }
        } else {
            Log.i(TAG, "当前为外网状态，校验本地库的账号密码");
            userDto = userDao.findUserByUserName(vo.getUsername());
            //本地登录失败
            if (userDto == null) {
                Message msg = Message.obtain();
                msg.obj = "账号不存在！";
                activity.getHandler().sendMessage(msg);
                return new BaseDto<>(300, "");

            }
            //本地登录失败
            else if (!(vo.getPassword().equals(userDto.getPassword()) || "000000".equals(vo.getPassword()))) {
                Message msg = Message.obtain();
                msg.obj = "用户名密码错误!";
                activity.getHandler().sendMessage(msg);
                return new BaseDto<>(300, "");

            } else {
                SPUtil.putData(Constant.SP.SP, Constant.SP.USER, userDto.getUsername());
                LoginDto loginDto = new LoginDto();
                if (userDto != null) {
                    loginDto.setUserAccount(userDto.getUsername());
                    loginDto.setUserName(userDto.getUsername());
                }
                return new BaseDto(loginDto);
            }

        }


    }

    /**
     * 属于服务器登录失败
     *
     * @param vo
     * @return
     */
    private String getLoginSession(LoginVo vo) {

        LoginCollectionVo loginCollectionVo = new LoginCollectionVo();
        loginCollectionVo.setAccount(vo.getUsername());
        loginCollectionVo.setPassword(vo.getPassword());
        loginCollectionVo.setMerchantId(Constant.Server.merchantId);
        loginCollectionVo.setPlatform(Constant.Server.platform);

        String loginCollectionJson = JSON.toJSON(loginCollectionVo).toString();
        try {
            Log.i(TAG, "请求参数loginCollectionJson:" + loginCollectionJson);
            Response response = HttpUtils.post(Constant.Server.ROOT_URL + "login/", loginCollectionJson);
            Log.i(TAG, "登陆接口返回response:" + response);

            String rtn = response.body().string();
            Log.i(TAG, "登陆接口返回内容:" + rtn);
            Document doc = DocumentHelper.parseText(rtn);
            JSONObject json = new JSONObject();
            Dom4jUtil.dom4j2Json(doc.getRootElement(), json);
            JSONObject jsonObjectTemp = (JSONObject) json.get("data");

            if (EmptyUtils.isNotEmpty(jsonObjectTemp)) {

                return jsonObjectTemp.get("session") + "";

            } else {
                String code = (String) json.get("code");
                String msg = (String) json.get("msg");
                Message message = Message.obtain();
                message.obj = msg + "-" + code;
                activity.getHandler().sendMessage(message);
                return null;
            }


        } catch (ServerException e) {

            Message msg = Message.obtain();
            msg.obj = e.getMsg();
            activity.getHandler().sendMessage(msg);
            return null;

        } catch (Exception e1) {

            Message msg = Message.obtain();

            msg.obj = e1.getMessage();

            activity.getHandler().sendMessage(msg);
            return null;

        }

    }


}
